

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=&#34;auto&#34;>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" type="image/png" href="/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  
    <meta name="baidu-site-verification" content="jre71SFl7b" />
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="">
  <meta name="author" content="lixinsta">
  <meta name="keywords" content="">
  <title>JS DOM操作——节点 - 自学前端的程序猿</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    
    <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/vs2015.min.css" />
  

  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_6peoq002giu.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_pjno9b9zyxs.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.0.2"><link rel="alternate" href="/atom.xml" title="自学前端的程序猿" type="application/atom+xml">
</head>


<body>
  <header style="height: 40vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>自学前端的程序猿</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item dropdown">
              <a class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                <i class="iconfont icon-images"></i>
                思维导图
              </a>
              <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                
                  
                  
                  
                  <a class="dropdown-item" target="_blank" rel="noopener" href="https://www.processon.com/view/5f3944647d9c0806d41a7d7a#map">
                    
                    HTML
                  </a>
                
                  
                  
                  
                  <a class="dropdown-item" target="_blank" rel="noopener" href="https://www.processon.com/view/5f3a1982079129531b5ec238#map">
                    
                    CSS
                  </a>
                
                  
                  
                  
                  <a class="dropdown-item" target="_blank" rel="noopener" href="https://hexo.fluid-dev.com/docs/icon/">
                    
                    JavaScript
                  </a>
                
              </div>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;</a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" href="javascript:">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner intro-2" id="background" parallax=true
         style="background: url('/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container page-header text-center fade-in-up">
            <span class="h2" id="subtitle">
              
            </span>

            
              
  <div class="mt-3 post-meta">
    <i class="iconfont icon-date-fill" aria-hidden="true"></i>
    <time datetime="2020-08-19 21:50" pubdate>
      2020年8月19日 晚上
    </time>
  </div>


<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      2.3k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      32
       分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto" id="post">
            <!-- SEO header -->
            <h1 style="display: none">JS DOM操作——节点</h1>
            
            <div class="markdown-body" id="post-body">
              <h1 id="节点概述"><a href="#节点概述" class="headerlink" title="节点概述"></a>节点概述</h1><p>​    网页中的所有内容都是节点（标签、属性、文本、注释等），在DOM 中，节点使用 node 来表示。</p>
<p>​    HTML DOM 树中的所有节点均可通过 JavaScript 进行访问，所有 HTML 元素（节点）均可被修改，也可以创建或删除。</p>
<p><img src="./1550970944363.png" srcset="/img/loading.gif" alt="1550970944363"></p>
<p>​    一般地，节点至少拥有nodeType（节点类型）、nodeName（节点名称）和nodeValue（节点值）这三个基本属性。</p>
<blockquote>
<ul>
<li><p>元素节点  nodeType 为  1</p>
</li>
<li><p>属性节点  nodeType 为  2</p>
</li>
<li><p>文本节点  nodeType  为  3 （文本节点包含文字、空格、换行等）</p>
<p><strong>实际开发中，节点主要操作的是元素节点</strong></p>
</li>
</ul>
</blockquote>
<h1 id="节点层级"><a href="#节点层级" class="headerlink" title="节点层级"></a>节点层级</h1><p>​    利用 DOM 树可以把节点划分为不同的层级关系，常见的是<strong>父子兄层级关系</strong>。</p>
<p> <img src="./1550971058781.png" srcset="/img/loading.gif" alt="1550971058781"></p>
<h1 id="获取节点"><a href="#获取节点" class="headerlink" title="获取节点"></a>获取节点</h1><h2 id="父级节点"><a href="#父级节点" class="headerlink" title="父级节点"></a>父级节点</h2><blockquote>
<p>node.parentNode</p>
<ul>
<li>parentNode 属性可返回某节点的父节点 ，注意<strong>是最近一个父节点</strong></li>
<li>如果指定的节点没有父节点则返回 null</li>
</ul>
</blockquote>
<div class="hljs"><pre><code class="hljs js">&lt;div <span class="hljs-class"><span class="hljs-keyword">class</span></span>=<span class="hljs-string">&quot;demo&quot;</span>&gt;
    &lt;div <span class="hljs-class"><span class="hljs-keyword">class</span></span>=<span class="hljs-string">&quot;box&quot;</span>&gt;
        &lt;span <span class="hljs-class"><span class="hljs-keyword">class</span></span>=<span class="hljs-string">&quot;erweima&quot;</span>&gt;×&lt;/span&gt;
    &lt;/div&gt;
&lt;/div&gt;
&lt;script&gt;
    <span class="hljs-comment">// 1. 父节点 parentNode</span>
    <span class="hljs-keyword">var</span> erweima = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">&#x27;.erweima&#x27;</span>);
    <span class="hljs-comment">// var box = document.querySelector(&#x27;.box&#x27;);</span>
    <span class="hljs-comment">// 得到的是离元素最近的父级节点(亲爸爸) 如果找不到父节点就返回为 null</span>
    <span class="hljs-built_in">console</span>.log(erweima.parentNode);
&lt;/script&gt;</code></pre></div>

<h2 id="子节点"><a href="#子节点" class="headerlink" title="子节点"></a>子节点</h2><p><strong>所有子节点</strong></p>
<blockquote>
<p>parentNode.childNodes（标准）返回指定节点的子节点的集合，<strong>该集合为即时更新的集合。</strong></p>
<p><strong>返回值里面包含了所有的子节点，包括元素节点，文本节点等。</strong></p>
<p><strong>如果只想要获得里面的元素节点，则需要专门处理。所以一般不提倡使用 childNodes</strong></p>
</blockquote>
<p><strong>子元素节点</strong></p>
<blockquote>
<p>parentNode.children（非标准）</p>
<p>这是一个只读属性，返回所有的子元素节点。<strong>只返回子元素节点，其余节点不返回。</strong></p>
<p>虽然 children 是一个非标准，但是各个浏览器都支持，因此可以放心使用。</p>
</blockquote>
<div class="hljs"><pre><code class="hljs js">&lt;ul&gt;
    &lt;li&gt;我是li&lt;/li&gt;
    &lt;li&gt;我是li&lt;/li&gt;
    &lt;li&gt;我是li&lt;/li&gt;
    &lt;li&gt;我是li&lt;/li&gt;
&lt;/ul&gt;
&lt;script&gt;
    <span class="hljs-comment">// DOM 提供的方法（API）获取</span>
    <span class="hljs-keyword">var</span> ul = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">&#x27;ul&#x27;</span>);
    <span class="hljs-keyword">var</span> lis = ul.querySelectorAll(<span class="hljs-string">&#x27;li&#x27;</span>);
    <span class="hljs-comment">// 1. 子节点  childNodes 所有的子节点 包含 元素节点 文本节点等等</span>
    <span class="hljs-built_in">console</span>.log(ul.childNodes);
    <span class="hljs-built_in">console</span>.log(ul.childNodes[<span class="hljs-number">0</span>].nodeType);
    <span class="hljs-built_in">console</span>.log(ul.childNodes[<span class="hljs-number">1</span>].nodeType);
    <span class="hljs-comment">// 2. children 获取所有的子元素节点 也是我们实际开发常用的</span>
    <span class="hljs-built_in">console</span>.log(ul.children);
&lt;/script&gt;</code></pre></div>

<blockquote>
<p>第一个子节点：parentNode.firstChild</p>
<p>最后一个子节点：parentNode.lastChild</p>
<p>第一个子元素节点：parentNode.firstElementChild（返回第一个子元素节点，找不到返回 null）</p>
<p>最后一个子元素节点：parentNode.lastElementChild（返回最后一个子元素节点，找不到返回 null）</p>
</blockquote>
<p>​    实际开发中，firstChild 和 lastChild 包含其他节点，操作不方便，而 firstElementChild 和 lastElementChild 又有兼容性问题，那么我们如何获取第一个子元素节点或最后一个子元素节点呢？</p>
<p><strong>解决方案：</strong></p>
<ol>
<li>如果想要第一个子元素节点，可以使用 parentNode.children[0]</li>
<li>如果想要获取最后一个子元素节点，可以使用  parentNode.children[parentNode.children.length - 1]</li>
</ol>
<div class="hljs"><pre><code class="hljs js">&lt;ol&gt;
    &lt;li&gt;我是li1&lt;/li&gt;
    &lt;li&gt;我是li2&lt;/li&gt;
    &lt;li&gt;我是li3&lt;/li&gt;
    &lt;li&gt;我是li4&lt;/li&gt;
    &lt;li&gt;我是li5&lt;/li&gt;
&lt;/ol&gt;
&lt;script&gt;
    <span class="hljs-keyword">var</span> ol = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">&#x27;ol&#x27;</span>);
    <span class="hljs-comment">// 1. firstChild 第一个子节点 不管是文本节点还是元素节点</span>
    <span class="hljs-built_in">console</span>.log(ol.firstChild);
    <span class="hljs-built_in">console</span>.log(ol.lastChild);
    <span class="hljs-comment">// 2. firstElementChild 返回第一个子元素节点 ie9才支持</span>
    <span class="hljs-built_in">console</span>.log(ol.firstElementChild);
    <span class="hljs-built_in">console</span>.log(ol.lastElementChild);
    <span class="hljs-comment">// 3. 实际开发的写法  既没有兼容性问题又返回第一个子元素</span>
    <span class="hljs-built_in">console</span>.log(ol.children[<span class="hljs-number">0</span>]);
    <span class="hljs-built_in">console</span>.log(ol.children[ol.children.length - <span class="hljs-number">1</span>]);
&lt;/script&gt;</code></pre></div>

<h2 id="兄弟节点"><a href="#兄弟节点" class="headerlink" title="兄弟节点"></a>兄弟节点</h2><blockquote>
<p><strong>下一个兄弟节点</strong></p>
<p>node.nextSibling    返回当前元素的下一个兄弟节点，找不到返回 null</p>
<p><strong>上一个兄弟节点</strong></p>
<p>node.previousSibling  返回当前元素上一个兄弟节点，找不到返回 null</p>
</blockquote>
<div class="hljs"><pre><code class="hljs js">&lt;div&gt;我是div&lt;/div&gt;
&lt;span&gt;我是span&lt;/span&gt;
&lt;script&gt;
    <span class="hljs-keyword">var</span> div = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">&#x27;div&#x27;</span>);
    <span class="hljs-comment">// 1.nextSibling 下一个兄弟节点 包含元素节点或者 文本节点等等</span>
    <span class="hljs-built_in">console</span>.log(div.nextSibling);
    <span class="hljs-built_in">console</span>.log(div.previousSibling);
    <span class="hljs-comment">// 2. nextElementSibling 得到下一个兄弟元素节点</span>
    <span class="hljs-built_in">console</span>.log(div.nextElementSibling);
    <span class="hljs-built_in">console</span>.log(div.previousElementSibling);
&lt;/script&gt;</code></pre></div>

<blockquote>
<p><strong>下一个兄弟元素节点（有兼容性问题）</strong></p>
<p>node.nextElementSibling</p>
<p><strong>上一个兄弟元素节点（有兼容性问题）</strong></p>
<p>node.nextpreviousElementSibling</p>
</blockquote>
<p>注意：nextElementSibling 和 previousElementSibling 都有兼容性问题，IE9 以上才支持。需要我们自己封装一个兼容性函数。</p>
<div class="hljs"><pre><code class="hljs js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getNextElementSibling</span>(<span class="hljs-params">element</span>) </span>&#123;
   <span class="hljs-keyword">var</span> el = element;
   <span class="hljs-keyword">while</span> (el = el.nextSibling) &#123;
     <span class="hljs-keyword">if</span> (el.nodeType === <span class="hljs-number">1</span>) &#123;
         <span class="hljs-keyword">return</span> el;
     &#125;
   &#125;
   <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
 &#125;</code></pre></div>

<h1 id="节点操作"><a href="#节点操作" class="headerlink" title="节点操作"></a>节点操作</h1><h2 id="创建节点"><a href="#创建节点" class="headerlink" title="创建节点"></a>创建节点</h2><blockquote>
<p>document.createElement(‘tagName’)  创建由 tagName 指定的 HTML 元素。因此这些元素原先不存在，是根据我们的需求动态生成的，所有<strong>也称之为动态创建元素节点。</strong></p>
</blockquote>
<h2 id="添加节点"><a href="#添加节点" class="headerlink" title="添加节点"></a>添加节点</h2><blockquote>
<p>node.appendChild(child)  将一个节点添加到指定父节点的列表<strong>末尾</strong>。类似于 css 里面的 after 伪元素</p>
<p>node.insertBefore(child,指定元素)  将一个节点添加到父节点的指定节点<strong>前面</strong>。类似于 css 里面的 before 伪元素</p>
</blockquote>
<div class="hljs"><pre><code class="hljs js">&lt;ul&gt;
    &lt;li&gt;<span class="hljs-number">123</span>&lt;/li&gt;
&lt;/ul&gt;
&lt;script&gt;
    <span class="hljs-comment">// 1. 创建节点元素节点</span>
    <span class="hljs-keyword">var</span> li = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">&#x27;li&#x27;</span>);
    <span class="hljs-comment">// 2. 添加节点 node.appendChild(child)  node 父级  child 是子级 后面追加元素</span>
    <span class="hljs-keyword">var</span> ul = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">&#x27;ul&#x27;</span>);
    ul.appendChild(li);
    <span class="hljs-comment">// 3. 添加节点 node.insertBefore(child, 指定元素);</span>
    <span class="hljs-keyword">var</span> lili = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">&#x27;li&#x27;</span>);
    ul.insertBefore(lili, ul.children[<span class="hljs-number">0</span>]);
    <span class="hljs-comment">// 4. 我们想要页面添加一个新的元素 ： 1. 创建元素 2. 添加元素</span>
&lt;/script&gt;</code></pre></div>

<h2 id="删除节点"><a href="#删除节点" class="headerlink" title="删除节点"></a>删除节点</h2><p>node.removeChild() 方法从 node节点中删除一个子节点，返回删除的节点。</p>
<div class="hljs"><pre><code class="hljs js">&lt;button&gt;删除&lt;/button&gt;
&lt;ul&gt;
    &lt;li&gt;熊大&lt;/li&gt;
    &lt;li&gt;熊二&lt;/li&gt;
    &lt;li&gt;光头强&lt;/li&gt;
&lt;/ul&gt;
&lt;script&gt;
    <span class="hljs-comment">// 1.获取元素</span>
    <span class="hljs-keyword">var</span> ul = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">&#x27;ul&#x27;</span>);
    <span class="hljs-keyword">var</span> btn = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">&#x27;button&#x27;</span>);
    <span class="hljs-comment">// 2. 删除元素  node.removeChild(child)</span>
    <span class="hljs-comment">// ul.removeChild(ul.children[0]);</span>
    <span class="hljs-comment">// 3. 点击按钮依次删除里面的孩子</span>
    btn.onclick = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>&#123;
        <span class="hljs-keyword">if</span> (ul.children.length == <span class="hljs-number">0</span>) &#123;
            <span class="hljs-built_in">this</span>.disabled = <span class="hljs-literal">true</span>;
        &#125; <span class="hljs-keyword">else</span> &#123;
            ul.removeChild(ul.children[<span class="hljs-number">0</span>]);
        &#125;
    &#125;
&lt;/script&gt;</code></pre></div>

<h2 id="复制（克隆）节点"><a href="#复制（克隆）节点" class="headerlink" title="复制（克隆）节点"></a>复制（克隆）节点</h2><blockquote>
<p>node.cloneNode()  返回调用该方法的节点的一个副本。也称为克隆节点/拷贝节点</p>
<p>注意：</p>
<ol>
<li>如果括号参数为空或者 <code>flase</code>，则是浅拷贝。即只克隆节点本身，布可隆里面的子节点。</li>
<li>如果参数为 <code>true</code>。则是深拷贝，会复制节点本身以及里面的所有子节点。</li>
</ol>
</blockquote>
<div class="hljs"><pre><code class="hljs js">&lt;ul&gt;
    &lt;li&gt;<span class="hljs-number">1111</span>&lt;/li&gt;
    &lt;li&gt;<span class="hljs-number">2</span>&lt;/li&gt;
    &lt;li&gt;<span class="hljs-number">3</span>&lt;/li&gt;
&lt;/ul&gt;
&lt;script&gt;
    <span class="hljs-keyword">var</span> ul = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">&#x27;ul&#x27;</span>);
    <span class="hljs-comment">// 1. node.cloneNode(); 括号为空或者里面是false 浅拷贝 只复制标签不复制里面的内容</span>
    <span class="hljs-comment">// 2. node.cloneNode(true); 括号为true 深拷贝 复制标签复制里面的内容</span>
    <span class="hljs-keyword">var</span> lili = ul.children[<span class="hljs-number">0</span>].cloneNode(<span class="hljs-literal">true</span>);
    ul.appendChild(lili);
&lt;/script&gt;</code></pre></div>

<h1 id="创建元素的三种方式"><a href="#创建元素的三种方式" class="headerlink" title="创建元素的三种方式"></a>创建元素的三种方式</h1><blockquote>
<ul>
<li>document.write()</li>
<li>element.innerHTML()</li>
<li>document.createElement()</li>
</ul>
</blockquote>
<p><strong>区别：</strong></p>
<ol>
<li><p>document.write 是直接将内容写入页面的内容流，但是文档流执行完毕，则它<strong>会导致页面全部重绘</strong></p>
</li>
<li><p>innerHTML 将内容写入某个 DOM 节点，不会导致页面重绘</p>
</li>
<li><p>innerHTML 创建多个元素效率更高（不要拼接字符串，采用数组的形式拼接），结构稍微复杂</p>
</li>
<li><p>createElement()  创建多个元素效率稍微低一些，但是结构清晰</p>
<p><strong>总结：不同浏览器下，innerHTML 效率要比 createElement 高</strong></p>
</li>
</ol>
<div class="hljs"><pre><code class="hljs js">&lt;script&gt;
    <span class="hljs-comment">// 三种创建元素方式区别 </span>
    <span class="hljs-comment">// 1. document.write() 创建元素  如果页面文档流加载完毕，再调用这句话会导致页面重绘</span>
     <span class="hljs-keyword">var</span> btn = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">&#x27;button&#x27;</span>);
     btn.onclick = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>&#123;
         <span class="hljs-built_in">document</span>.write(<span class="hljs-string">&#x27;&lt;div&gt;123&lt;/div&gt;&#x27;</span>);
     &#125;

    <span class="hljs-comment">// 2. innerHTML 创建元素</span>
    <span class="hljs-keyword">var</span> inner = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">&#x27;.inner&#x27;</span>);
     <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt;= <span class="hljs-number">100</span>; i++) &#123;
         inner.innerHTML += <span class="hljs-string">&#x27;&lt;a href=&quot;#&quot;&gt;百度&lt;/a&gt;&#x27;</span>
     &#125;
    <span class="hljs-keyword">var</span> arr = [];
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt;= <span class="hljs-number">100</span>; i++) &#123;
        arr.push(<span class="hljs-string">&#x27;&lt;a href=&quot;#&quot;&gt;百度&lt;/a&gt;&#x27;</span>);
    &#125;
    inner.innerHTML = arr.join(<span class="hljs-string">&#x27;&#x27;</span>);
    <span class="hljs-comment">// 3. document.createElement() 创建元素</span>
    <span class="hljs-keyword">var</span> create = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">&#x27;.create&#x27;</span>);
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt;= <span class="hljs-number">100</span>; i++) &#123;
        <span class="hljs-keyword">var</span> a = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">&#x27;a&#x27;</span>);
        create.appendChild(a);
    &#125;
&lt;/script&gt;</code></pre></div>



<h2 id="innerTHML和createElement效率对比"><a href="#innerTHML和createElement效率对比" class="headerlink" title="innerTHML和createElement效率对比"></a>innerTHML和createElement效率对比</h2><p><strong>innerHTML字符串拼接方式（效率低）</strong></p>
<div class="hljs"><pre><code class="hljs js">&lt;script&gt;
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fn</span>(<span class="hljs-params"></span>) </span>&#123;
        <span class="hljs-keyword">var</span> d1 = +<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>();
        <span class="hljs-keyword">var</span> str = <span class="hljs-string">&#x27;&#x27;</span>;
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">1000</span>; i++) &#123;
            <span class="hljs-built_in">document</span>.body.innerHTML += <span class="hljs-string">&#x27;&lt;div style=&quot;width:100px; height:2px; border:1px solid blue;&quot;&gt;&lt;/div&gt;&#x27;</span>;
        &#125;
        <span class="hljs-keyword">var</span> d2 = +<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>();
        <span class="hljs-built_in">console</span>.log(d2 - d1);
    &#125;
    fn();
&lt;/script&gt;</code></pre></div>

<p><strong>createElement方式（效率一般）</strong></p>
<div class="hljs"><pre><code class="hljs js">&lt;script&gt;
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fn</span>(<span class="hljs-params"></span>) </span>&#123;
        <span class="hljs-keyword">var</span> d1 = +<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>();

        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">1000</span>; i++) &#123;
            <span class="hljs-keyword">var</span> div = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">&#x27;div&#x27;</span>);
            div.style.width = <span class="hljs-string">&#x27;100px&#x27;</span>;
            div.style.height = <span class="hljs-string">&#x27;2px&#x27;</span>;
            div.style.border = <span class="hljs-string">&#x27;1px solid red&#x27;</span>;
            <span class="hljs-built_in">document</span>.body.appendChild(div);
        &#125;
        <span class="hljs-keyword">var</span> d2 = +<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>();
        <span class="hljs-built_in">console</span>.log(d2 - d1);
    &#125;
    fn();
&lt;/script&gt;</code></pre></div>

<p><strong>innerHTML数组方式（效率高）</strong></p>
<div class="hljs"><pre><code class="hljs js">&lt;script&gt;
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fn</span>(<span class="hljs-params"></span>) </span>&#123;
        <span class="hljs-keyword">var</span> d1 = +<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>();
        <span class="hljs-keyword">var</span> array = [];
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">1000</span>; i++) &#123;
            array.push(<span class="hljs-string">&#x27;&lt;div style=&quot;width:100px; height:2px; border:1px solid blue;&quot;&gt;&lt;/div&gt;&#x27;</span>);
        &#125;
        <span class="hljs-built_in">document</span>.body.innerHTML = array.join(<span class="hljs-string">&#x27;&#x27;</span>);
        <span class="hljs-keyword">var</span> d2 = +<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>();
        <span class="hljs-built_in">console</span>.log(d2 - d1);
    &#125;
    fn();
&lt;/script&gt;</code></pre></div>

<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/kity@2.0.4/dist/kity.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/kityminder-core@1.4.50/dist/kityminder.core.min.js"></script><script defer="true" type="text/javascript" src="https://cdn.jsdelivr.net/npm/hexo-simple-mindmap@0.2.0/dist/mindmap.min.js"></script><link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/hexo-simple-mindmap@0.2.0/dist/mindmap.min.css">
            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/%E5%89%8D%E7%AB%AF/">前端</a>
                    
                      <a class="hover-with-bg" href="/categories/%E5%89%8D%E7%AB%AF/JavaScript/">JavaScript</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/JavaScript/">JavaScript</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2020/09/01/Cookie%E6%80%BB%E7%BB%93/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Cookie总结</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2020/08/19/JS%20DOM%E6%93%8D%E4%BD%9C%E2%80%94%E2%80%94%E4%BA%8B%E4%BB%B6/">
                        <span class="hidden-mobile">JS DOM操作——事件</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
              <!-- Comments -->
              <article class="comments" id="comments">
                
                

              </article>
            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  

  <footer class="mt-5">
  <div class="text-center py-3">

  
	  <!-- 博客运营时间 -->
	  <div>
		  <span id="timeDate">载入天数...</span>
		  <span id="times">载入时分秒...</span>
		  <script>
		  var now = new Date();
		  function createtime(){
			  var grt= new Date("08/14/2020 00:00:00");//此处修改你的建站时间或者网站上线时间
			  now.setTime(now.getTime()+250);
			  days = (now - grt ) / 1000 / 60 / 60 / 24;
			  dnum = Math.floor(days);
			  hours = (now - grt ) / 1000 / 60 / 60 - (24 * dnum);
			  hnum = Math.floor(hours);
			  if(String(hnum).length ==1 ){
				  hnum = "0" + hnum;
			  }
			  minutes = (now - grt ) / 1000 /60 - (24 * 60 * dnum) - (60 * hnum);
			  mnum = Math.floor(minutes);
			  if(String(mnum).length ==1 ){
						mnum = "0" + mnum;
			  }
			  seconds = (now - grt ) / 1000 - (24 * 60 * 60 * dnum) - (60 * 60 * hnum) - (60 * mnum);
			  snum = Math.round(seconds);
			  if(String(snum).length ==1 ){
						snum = "0" + snum;
			  }
			  document.getElementById("timeDate").innerHTML = "本站安全运行&nbsp"+dnum+"&nbsp天";
			  document.getElementById("times").innerHTML = hnum + "&nbsp小时&nbsp" + mnum + "&nbsp分&nbsp" + snum + "&nbsp秒";
		  }
		  setInterval("createtime()",250);
		  </script>
		</div>
		
		
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


		

		
	
		<!-- 一言 -->
		<p id="hitokoto">:D 获取中...</p>
		<script>
		  fetch('https://v1.hitokoto.cn')
			.then(response => response.json())
			.then(data => {
			  const hitokoto = document.getElementById('hitokoto')
			  hitokoto.innerText = data.hitokoto
			  })
			  .catch(console.error)
		</script>
	</div>
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/js/lazyload.js" ></script>
  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/js/clipboard-use.js" ></script>



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: '#post-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 0,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "JS DOM操作——节点&nbsp;",
      ],
      cursorChar: "_",
      typeSpeed: 70,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    var path = "/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>




















</body>
</html>
